<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>connect</title>
</head>

<body>
  <div id='app'>Connect</div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script>
    let websock = null
    let socketTimer = null
    let socketParam = {
      type: 'test'
    }
    let vm = new Vue({
      el: "#app",
      template: `
      <div>
        <textarea v-model="textVal"></textarea>
        <button @click='send'>send</button>
        <ul><li v-for="res in receivedList">{{res}}</li></ul>
      </div>
      `,
      data() {
        return {
          textVal: '',
          receivedList: [],
          socketUrl: 'ws://localhost:8088',
          timerWS: null, // 用于ws重连
          timerCountWS: 0, // 用于重连计数，0-立刻开始重连，非0-1min重连一次。
          timerFlagWS: true // 跳转页面了不再重连
        }
      },
      mounted() {
        this.initWebsocket();
      },
      destroyed() {
        this.timerFlagWS = false
        this.timerCountWS = 0
        clearTimeout(this.timerWS)
        if (websock !== null) {
          websock.close()
          websock = null
        }
        clearTimeout(socketTimer)
      },
      methods: {
        send() {
          this.websocketsend(this.textVal);
          this.textVal = '';
        },
        initWebsocket() {
          console.log('init');
          if (typeof WebSocket !== 'undefined') {
            this.timerCountWS++
            // 浏览器支持Websocket通信协议 开启长连接
            websock = new WebSocket(this.socketUrl)
            websock.onopen = this.websocketonopen
            websock.onclose = this.websocketclose
            websock.onerror = this.websocketonerror
            websock.onmessage = this.websocketonmessage
          } else {
            // 浏览器不支持Websocket通信协议
            this.$message.info('当前浏览器不支持Websocket通信协议，建议使用Chrome或者Firefox浏览器！')
          }
        },
        // 开启
        websocketonopen() {
          console.log('websocketonopen [test]')
          this.timerCountWS = 0
          this.threadPoxi()
        },
        // 关闭
        websocketclose(e) {
          console.log(e, 'websocketclose [test]')
          let self = this
          if (self.timerCountWS === 0) {
            if (self.timerFlagWS && e.code === 1006) self.initWebsocket()
            console.log('websocket reconnect:[test ' + self.timerCountWS + ']', self.timerFlagWS)
          } else {
            clearTimeout(self.timerWS)
            self.timerWS = setTimeout(() => {
              if (self.timerFlagWS && e.code === 1006) self.initWebsocket()
              console.log('websocket reconnect:[test ' + self.timerCountWS + ']', self.timerFlagWS)
            }, 6000)
          }
        },
        // 错误
        websocketonerror(e) {
          console.log('websocketonerror [test]')
        },
        // 数据接收
        websocketonmessage(e) {
          let res = JSON.stringify(e.data)
          console.log(res)
          this.receivedList.push(res);
        },
        threadPoxi() {
          // 参数
          let self = this
          // 若是ws开启状态
          if (websock.readyState === websock.OPEN) {
            console.log('websock.OPEN, websock.send start... [test]')
            self.websocketsend(socketParam)
          } else if (websock.readyState === websock.CONNECTING) {
            // 若是正在开启状态 则等待300毫秒 再调threadPoxi判断状态
            console.log('websock.CONNECTING, please wait 300ms... [test]')
            clearTimeout(socketTimer)
            socketTimer = setTimeout(() => {
              self.threadPoxi()
            }, 300)
          } else {
            // 若未开启 初始化websocket
            console.log('websock is not open, wait for reboot... [test]')
            self.initWebSocket()
          }
        },
        // 数据发送
        websocketsend(param) {
          websock.send(JSON.stringify(param))
        }
      }
    });
  </script>

</body>

</html>
